---
interface Breadcrumb {
  name: string;
  path: string;
}

export interface Props {
  pageType: 'filter' | 'grid' | 'article'; 
  pathSegments?: string[]; // 路径段数组
  searchParams?: URLSearchParams; // 搜索参数
  articleTitle?: string; // 文章标题（仅在文章详情页使用）
  path?: string; // 当前路径
}

const {
  pageType,
  pathSegments = [],
  searchParams = new URLSearchParams(),
  articleTitle = '',
  path = ''
} = Astro.props;

// 计算面包屑
const breadcrumbs: Breadcrumb[] = pathSegments
  .filter(segment => segment.trim() !== '')
  .map((segment, index, array) => {
    const path = array.slice(0, index + 1).join('/');
    return { name: segment, path };
  });
---

<div class="breadcrumb flex items-center justify-between w-full flex-wrap sm:flex-nowrap" data-page-type={pageType}>
  <div class="breadcrumb-path flex items-center text-sm overflow-hidden">
    <!-- 文章列表链接 - 根据当前页面类型决定链接 -->
    <a href={'/articles/'} class="breadcrumb-home text-secondary-600 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 flex items-center flex-shrink-0">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor">
        <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd" />
      </svg>
      文章
    </a>

    <!-- 网格视图或文章详情中的目录路径 -->
    {(pageType === 'grid' || (pageType === 'article' && breadcrumbs.length > 0)) && (
      <div class="breadcrumb-segments flex items-center overflow-hidden" data-segments-count={breadcrumbs.length}>
        <span class="breadcrumb-separator mx-2 text-secondary-300 dark:text-secondary-600 flex-shrink-0">/</span>
        
        <!-- 移动端使用智能截断 -->
        <div class="breadcrumb-mobile flex md:hidden items-center">
          {breadcrumbs.length > 2 ? (
            <>
              <!-- 第一个路径段 -->
              <a 
                href={`/articles/${breadcrumbs[0].path}/`} 
                class="breadcrumb-segment text-secondary-600 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 truncate max-w-[80px] sm:max-w-[100px] flex-shrink-0"
                data-segment-index="0"
              >
                {breadcrumbs[0].name}
              </a>
              
              <!-- 省略号 -->
              <span class="breadcrumb-ellipsis mx-2 text-secondary-300 dark:text-secondary-600 flex-shrink-0">...</span>
              
              <!-- 最后一个路径段 -->
              {breadcrumbs.length > 1 && (
                <a 
                  href={`/articles/${breadcrumbs[breadcrumbs.length - 1].path}/`} 
                  class="breadcrumb-segment text-secondary-600 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 truncate max-w-[80px] sm:max-w-[120px] flex-shrink-0"
                  data-segment-index={breadcrumbs.length - 1}
                >
                  {breadcrumbs[breadcrumbs.length - 1].name}
                </a>
              )}
            </>
          ) : (
            breadcrumbs.map((crumb: Breadcrumb, index: number) => {
              const crumbPath = breadcrumbs.slice(0, index + 1).map((b: Breadcrumb) => b.name).join('/');
              return (
                <span class="breadcrumb-item flex items-center flex-shrink-0">
                  {index > 0 && <span class="breadcrumb-separator mx-2 text-secondary-300 dark:text-secondary-600">/</span>}
                  <a 
                    href={`/articles/${crumbPath}/`} 
                    class="breadcrumb-segment text-secondary-600 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 truncate max-w-[100px] sm:max-w-[150px]"
                    data-segment-index={index}
                  >
                    {crumb.name}
                  </a>
                </span>
              );
            })
          )}
        </div>
        
        <!-- 桌面端显示全部路径段 -->
        <div class="breadcrumb-desktop hidden md:flex items-center flex-wrap">
          {breadcrumbs.map((crumb: Breadcrumb, index: number) => {
            const crumbPath = breadcrumbs.slice(0, index + 1).map((b: Breadcrumb) => b.name).join('/');
            return (
              <span class="breadcrumb-item flex items-center flex-shrink-0">
                {index > 0 && <span class="breadcrumb-separator mx-2 text-secondary-300 dark:text-secondary-600">/</span>}
                <a 
                  href={`/articles/${crumbPath}/`} 
                  class="breadcrumb-segment text-secondary-600 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 truncate max-w-[200px] lg:max-w-[250px] xl:max-w-[300px]"
                  data-segment-index={index}
                >
                  {crumb.name}
                </a>
              </span>
            );
          })}
        </div>
      </div>
    )}

    <!-- 筛选视图中的搜索参数展示 -->
    {pageType === 'filter' && searchParams.toString() && (
      <div class="breadcrumb-filter flex items-center overflow-hidden">
        <span class="breadcrumb-separator mx-2 text-secondary-300 dark:text-secondary-600 flex-shrink-0">/</span>
        <span class="breadcrumb-filter-label text-secondary-600 dark:text-secondary-400 truncate max-w-[120px] sm:max-w-[180px] md:max-w-[250px]">
          筛选
          {searchParams.toString() && <span class="breadcrumb-search-result ml-1">- 搜索结果</span>}
        </span>
      </div>
    )}

    <!-- 文章标题 - 仅在文章详情页显示 -->
    {pageType === 'article' && articleTitle && (
      <>
        <span class="breadcrumb-separator mx-2 text-secondary-300 dark:text-secondary-600 flex-shrink-0">/</span>
        <span class="breadcrumb-article-title text-secondary-600 dark:text-secondary-400 truncate max-w-[120px] sm:max-w-[180px] md:max-w-[250px]">{articleTitle}</span>
      </>
    )}
  </div>

  <!-- 视图切换按钮 - 仅在文章列表页面显示 -->
  {(pageType === 'filter' || pageType === 'grid') && (
    <div class="breadcrumb-view-switcher flex items-center gap-px flex-shrink-0 ml-auto">
      <a href={`/filtered${searchParams.toString() ? `?${searchParams.toString()}` : ''}`}
         class="breadcrumb-filter-btn px-3 py-1.5 flex items-center gap-1 ${
           pageType === 'filter' 
             ? 'text-primary-600 dark:text-primary-400 font-medium' 
             : 'text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400'
         }"
         data-view-type="filter"
         data-active={pageType === 'filter' ? 'true' : 'false'}
         data-astro-prefetch="hover">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
        </svg>
        <span class="hidden sm:inline text-xs">筛选</span>
      </a>
      <a href={path ? `/articles/${path}/` : `/articles/`}
         class="breadcrumb-grid-btn px-3 py-1.5 flex items-center gap-1 ${
           pageType === 'grid' 
             ? 'text-primary-600 dark:text-primary-400 font-medium' 
             : 'text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400'
         }"
         data-view-type="grid"
         data-active={pageType === 'grid' ? 'true' : 'false'}
         data-astro-prefetch="hover">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
        </svg>
        <span class="hidden sm:inline text-xs">网格</span>
      </a>
    </div>
  )}
  
  <!-- 文章详情页的返回按钮 -->
  {pageType === 'article' && (
    <div class="breadcrumb-back flex items-center shrink-0 ml-auto">
      <a
        href={`/articles/${path}/`}
        class="breadcrumb-back-btn text-secondary-500 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 flex items-center text-sm back-button"
        data-astro-prefetch="hover"
        data-path={`/articles/${path}/`}
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          class="h-4 w-4 mr-1"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M10 19l-7-7m0 0l7-7m-7 7h18"
          ></path>
        </svg>
        返回文章列表
      </a>
    </div>
  )}
</div> 

<script is:inline>
  // 面包屑控制器 - 自销毁模式
  (function() {
    // 集中管理所有事件监听器
    const allListeners = [];
    
    // 单独保存清理事件的监听器引用
    const cleanupListeners = [];
    
    // 内部状态管理
    const state = {
      isCleaningUp: false,
      lastActivePath: '',
      originalPushState: window.history.pushState,
      originalReplaceState: window.history.replaceState
    };
    
    // 添加事件监听器并记录，方便后续统一清理
    function addListener(element, eventType, handler, options) {
      if (!element) {
        console.warn(`[面包屑]尝试为不存在的元素添加事件`);
        return null;
      }

      element.addEventListener(eventType, handler, options);
      allListeners.push({ element, eventType, handler, options });
      return handler;
    }
    
    // 获取当前URL路径（与导航栏保持一致）
    function getCurrentPath() {
      const path = window.location.pathname;
      return path === '/' ? '/' : path.endsWith('/') ? path.slice(0, -1) : path;
    }
    
    // 解析URL参数
    function getUrlSearchParams() {
      return new URLSearchParams(window.location.search);
    }
    
    // 获取页面类型
    function getPageType(path) {
      if (path === '/filtered' || path.startsWith('/filtered')) {
        return 'filter';
      } else if (path.includes('/articles/') && !path.endsWith('/articles/')) {
        // 检查是否是文章详情页
        const segments = path.split('/').filter(s => s);
        // 如果路径中包含.html或.md，则认为是文章详情页
        if (segments.length > 1 && (segments[segments.length - 1].includes('.html') || segments[segments.length - 1].includes('.md'))) {
          return 'article';
        }
        return 'grid'; // 默认为网格视图
      } else {
        return 'grid'; // 默认为网格视图
      }
    }
    
    // 提取路径段
    function getPathSegments(path) {
      // 如果路径为空或根路径，直接返回空数组
      if (!path || path === '/') {
        return [];
      }
      
      // 标准化路径：移除结尾的斜杠并确保开头有斜杠
      let normalizedPath = path;
      if (normalizedPath.endsWith('/')) {
        normalizedPath = normalizedPath.slice(0, -1);
      }
      if (!normalizedPath.startsWith('/')) {
        normalizedPath = '/' + normalizedPath;
      }
      
      // 拆分路径为段落
      const segments = normalizedPath.split('/').filter(s => s);
      
      // 确定基础路径部分 - 在本应用中是 "articles"
      const basePathSegment = 'articles';
      
      // 移除基础路径部分（如果存在于路径的第一段）
      const pathWithoutBase = segments[0] === basePathSegment 
        ? segments.slice(1) 
        : segments;
      
      // 移除尾部的文件名（如果存在）
      let result = [...pathWithoutBase];
      const lastSegment = result[result.length - 1];
      if (lastSegment && (lastSegment.includes('.html') || lastSegment.includes('.md'))) {
        result.pop();
      }
      
      // 对每个段进行解码
      return result.map(segment => decodeURIComponent(segment));
    }
    
    // 获取文章标题（对于文章页面）
    function getArticleTitle(path) {
      // 从路径中提取文件名
      const segments = path.split('/');
      const fileName = segments[segments.length - 1];
      
      if (fileName && (fileName.includes('.html') || fileName.includes('.md'))) {
        // 移除扩展名，将连字符替换为空格，首字母大写
        let title = fileName.replace(/\.(html|md)$/, '')
                           .replace(/-/g, ' ')
                           .replace(/\b\w/g, c => c.toUpperCase());
        return title;
      }
      
      return '';
    }
    
    // 动态更新面包屑
    function updateBreadcrumbs() {
      // 获取当前路径和相关信息
      const currentPath = getCurrentPath();
      const pageType = getPageType(currentPath);
      const searchParams = getUrlSearchParams();
      const pathSegments = getPathSegments(currentPath);
      const articleTitle = pageType === 'article' ? getArticleTitle(currentPath) : '';
      
      // 获取面包屑容器
      const breadcrumbContainer = document.querySelector('.breadcrumb');
      if (!breadcrumbContainer) {
        console.warn('[面包屑]找不到面包屑容器，无法更新');
        return;
      }
      
      // 设置页面类型
      breadcrumbContainer.setAttribute('data-page-type', pageType);
      
      // 获取面包屑路径容器
      const breadcrumbPath = breadcrumbContainer.querySelector('.breadcrumb-path');
      if (!breadcrumbPath) {
        console.warn('[面包屑]找不到面包屑路径容器，无法更新');
        return;
      }
      
      // 生成路径面包屑HTML
      let breadcrumbsHtml = `
        <a href="/articles/" class="breadcrumb-home text-secondary-600 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 flex items-center flex-shrink-0">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd" />
          </svg>
          文章
        </a>
      `;
      
      // 网格视图或文章详情中的目录路径
      if (pageType === 'grid' || (pageType === 'article' && pathSegments.length > 0)) {
        breadcrumbsHtml += `<div class="breadcrumb-segments flex items-center overflow-hidden" data-segments-count="${pathSegments.length}">
          <span class="breadcrumb-separator mx-2 text-secondary-300 dark:text-secondary-600 flex-shrink-0">/</span>`;
        
        // 移动端使用智能截断
        breadcrumbsHtml += `<div class="breadcrumb-mobile flex md:hidden items-center">`;
        
        if (pathSegments.length > 2) {
          // 第一个路径段
          const firstSegment = pathSegments[0];
          const firstPath = encodeURIComponent(pathSegments.slice(0, 1).join('/'));
          
          breadcrumbsHtml += `
            <a 
              href="/articles/${firstPath}/" 
              class="breadcrumb-segment text-secondary-600 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 truncate max-w-[80px] sm:max-w-[100px] flex-shrink-0"
              data-segment-index="0"
            >
              ${firstSegment}
            </a>
            
            <span class="breadcrumb-ellipsis mx-2 text-secondary-300 dark:text-secondary-600 flex-shrink-0">...</span>
          `;
          
          // 最后一个路径段
          if (pathSegments.length > 1) {
            const lastSegment = pathSegments[pathSegments.length - 1];
            const lastPath = pathSegments.map(encodeURIComponent).join('/');
            
            breadcrumbsHtml += `
              <a 
                href="/articles/${lastPath}/" 
                class="breadcrumb-segment text-secondary-600 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 truncate max-w-[80px] sm:max-w-[120px] flex-shrink-0"
                data-segment-index="${pathSegments.length - 1}"
              >
                ${lastSegment}
              </a>
            `;
          }
        } else {
          // 如果段落不多，则全部显示
          breadcrumbsHtml += pathSegments.map((segment, index) => {
            const segmentPath = pathSegments.slice(0, index + 1).map(encodeURIComponent).join('/');
            return `
              <span class="breadcrumb-item flex items-center flex-shrink-0">
                ${index > 0 ? '<span class="breadcrumb-separator mx-2 text-secondary-300 dark:text-secondary-600">/</span>' : ''}
                <a 
                  href="/articles/${segmentPath}/" 
                  class="breadcrumb-segment text-secondary-600 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 truncate max-w-[100px] sm:max-w-[150px]"
                  data-segment-index="${index}"
                >
                  ${segment}
                </a>
              </span>
            `;
          }).join('');
        }
        
        breadcrumbsHtml += `</div>`;
        
        // 桌面端显示全部路径段
        breadcrumbsHtml += `<div class="breadcrumb-desktop hidden md:flex items-center flex-wrap">`;
        
        breadcrumbsHtml += pathSegments.map((segment, index) => {
          const segmentPath = pathSegments.slice(0, index + 1).map(encodeURIComponent).join('/');
          return `
            <span class="breadcrumb-item flex items-center flex-shrink-0">
              ${index > 0 ? '<span class="breadcrumb-separator mx-2 text-secondary-300 dark:text-secondary-600">/</span>' : ''}
              <a 
                href="/articles/${segmentPath}/" 
                class="breadcrumb-segment text-secondary-600 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 truncate max-w-[200px] lg:max-w-[250px] xl:max-w-[300px]"
                data-segment-index="${index}"
              >
                ${segment}
              </a>
            </span>
          `;
        }).join('');
        
        breadcrumbsHtml += `</div></div>`;
      }
      
      // 筛选视图中的搜索参数展示
      if (pageType === 'filter' && searchParams.toString()) {
        breadcrumbsHtml += `
          <div class="breadcrumb-filter flex items-center overflow-hidden">
            <span class="breadcrumb-separator mx-2 text-secondary-300 dark:text-secondary-600 flex-shrink-0">/</span>
            <span class="breadcrumb-filter-label text-secondary-600 dark:text-secondary-400 truncate max-w-[120px] sm:max-w-[180px] md:max-w-[250px]">
              筛选
              ${searchParams.toString() ? '<span class="breadcrumb-search-result ml-1">- 搜索结果</span>' : ''}
            </span>
          </div>
        `;
      }
      
      // 文章标题 - 仅在文章详情页显示
      if (pageType === 'article' && articleTitle) {
        breadcrumbsHtml += `
          <span class="breadcrumb-separator mx-2 text-secondary-300 dark:text-secondary-600 flex-shrink-0">/</span>
          <span class="breadcrumb-article-title text-secondary-600 dark:text-secondary-400 truncate max-w-[120px] sm:max-w-[180px] md:max-w-[250px]">${articleTitle}</span>
        `;
      }
      
      // 更新面包屑容器内容
      breadcrumbPath.innerHTML = breadcrumbsHtml;
      
      // 更新视图切换按钮
      updateViewSwitchButtons(pageType, currentPath, searchParams);
      
      // 更新返回按钮（对于文章页面）
      if (pageType === 'article') {
        updateBackButton(currentPath, pathSegments.join('/'));
      }
    }
    
    // 更新视图切换按钮
    function updateViewSwitchButtons(pageType, currentPath, searchParams) {
      // 获取视图切换按钮容器
      const viewSwitchContainer = document.querySelector('.breadcrumb-view-switcher');
      if (!viewSwitchContainer || !(pageType === 'filter' || pageType === 'grid')) {
        return;
      }
      
      const searchParamsStr = searchParams.toString() ? `?${searchParams.toString()}` : '';
      const pathStr = currentPath.includes('/articles/') ? currentPath.replace('/articles/', '') : '';
      
      // 生成视图切换按钮HTML
      const switchButtonsHtml = `
        <a href="/filtered${searchParamsStr}"
           class="breadcrumb-filter-btn px-3 py-1.5 flex items-center gap-1 ${
             pageType === 'filter' 
               ? 'text-primary-600 dark:text-primary-400 font-medium' 
               : 'text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400'
           }"
           data-view-type="filter"
           data-active="${pageType === 'filter' ? 'true' : 'false'}"
           data-astro-prefetch="hover">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
          </svg>
          <span class="hidden sm:inline text-xs">筛选</span>
        </a>
        <a href="${pathStr ? `/articles/${pathStr}/` : `/articles/`}"
           class="breadcrumb-grid-btn px-3 py-1.5 flex items-center gap-1 ${
             pageType === 'grid' 
               ? 'text-primary-600 dark:text-primary-400 font-medium' 
               : 'text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400'
           }"
           data-view-type="grid"
           data-active="${pageType === 'grid' ? 'true' : 'false'}"
           data-astro-prefetch="hover">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
          </svg>
          <span class="hidden sm:inline text-xs">网格</span>
        </a>
      `;
      
      // 更新视图切换按钮容器内容
      viewSwitchContainer.innerHTML = switchButtonsHtml;
    }
    
    // 更新返回按钮
    function updateBackButton(currentPath, pathWithoutFile) {
      // 获取面包屑容器
      const breadcrumbContainer = document.querySelector('.breadcrumb');
      if (!breadcrumbContainer) {
        return;
      }
      
      // 检查是否已有返回按钮容器
      let backButtonContainer = document.querySelector('.breadcrumb-back');
      
      // 如果没有返回按钮容器，创建一个
      if (!backButtonContainer) {
        backButtonContainer = document.createElement('div');
        backButtonContainer.className = 'breadcrumb-back flex items-center shrink-0 ml-auto';
        breadcrumbContainer.appendChild(backButtonContainer);
      }
      
      // 确保路径使用编码后的形式用于URL
      const encodedPath = pathWithoutFile.split('/').map(encodeURIComponent).join('/');
      
      // 生成返回按钮HTML
      const backButtonHtml = `
        <a
          href="/articles/${encodedPath}/"
          class="breadcrumb-back-btn text-secondary-500 dark:text-secondary-400 hover:text-primary-600 dark:hover:text-primary-400 flex items-center text-sm back-button"
          data-astro-prefetch="hover"
          data-path="/articles/${encodedPath}/"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            class="h-4 w-4 mr-1"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M10 19l-7-7m0 0l7-7m-7 7h18"
            ></path>
          </svg>
          返回文章列表
        </a>
      `;
      
      // 更新返回按钮容器内容
      backButtonContainer.innerHTML = backButtonHtml;
      
      // 设置返回按钮功能
      setupBackButton();
    }
    
    // 添加路径变化检测和自动更新
    function setupPathChangeDetection() {
      let lastPathChecked = getCurrentPath();
      
      // 统一的路径变化处理函数
      function handlePathChange() {
        // 如果正在清理中，不要继续更新
        if (state.isCleaningUp) {
          return;
        }
        
        const currentPath = getCurrentPath();
        if (currentPath !== lastPathChecked) {
          // 更新面包屑
          updateBreadcrumbs();
          
          // 更新记录的路径
          lastPathChecked = currentPath;
        }
      }
      
      // 监听hashchange事件 - 当URL的hash部分改变时触发
      addListener(window, 'hashchange', () => {
        if (state.isCleaningUp) return;
        handlePathChange();
      });
      
      // 监听popstate事件
      addListener(window, 'popstate', () => {
        if (state.isCleaningUp) return;
        handlePathChange();
      });
      
      // 监听页面转换事件，设置清理标志
      addListener(document, 'page-transition', () => {
        // 设置清理标志，阻止后续的handlePathChange调用
        state.isCleaningUp = true;
      });
      
      // 监听页面内容替换完成后更新面包屑
      addListener(document, 'swup:contentReplaced', () => {
        if (state.isCleaningUp) return;
        setTimeout(() => {
          // 在DOM更新后，重新计算面包屑
          handlePathChange();
        }, 10);
      });
      
      // 设置History API监控
      setupHistoryMonitoring();
    }
    
    // 设置History API监控
    function setupHistoryMonitoring() {
      // 保存初始状态
      state.originalPushState = window.history.pushState;
      state.originalReplaceState = window.history.replaceState;
      
      // 重写pushState
      window.history.pushState = function() {
        // 如果正在清理中，不要执行被重写的方法，直接调用原始方法
        if (state.isCleaningUp) {
          return state.originalPushState.apply(this, arguments);
        }
        
        state.originalPushState.apply(this, arguments);
        setTimeout(() => {
          const currentPath = getCurrentPath();
          if (currentPath !== state.lastActivePath) {
            updateBreadcrumbs();
            state.lastActivePath = currentPath;
          }
        }, 10);
      };
      
      // 重写replaceState
      window.history.replaceState = function() {
        // 如果正在清理中，不要执行被重写的方法，直接调用原始方法
        if (state.isCleaningUp) {
          return state.originalReplaceState.apply(this, arguments);
        }
        
        state.originalReplaceState.apply(this, arguments);
        setTimeout(() => {
          const currentPath = getCurrentPath();
          if (currentPath !== state.lastActivePath) {
            updateBreadcrumbs();
            state.lastActivePath = currentPath;
          }
        }, 10);
      };
    }
    
    // 统一的清理函数，执行完整清理并自销毁
    function selfDestruct() {
      // 标记清理状态
      state.isCleaningUp = true;
      
      // 1. 移除所有普通事件监听器
      allListeners.forEach(({ element, eventType, handler, options }) => {
        try {
          element.removeEventListener(eventType, handler, options);
        } catch (err) {
          console.error(`[面包屑] 移除事件监听器出错:`, err);
        }
      });
      
      // 清空监听器数组
      allListeners.length = 0;
      
      // 恢复原始的history方法
      if (state.originalPushState && state.originalReplaceState) {
        try {
          // 立即恢复原始方法，确保后续pushState调用直接使用原始方法
          const tempOriginalPushState = state.originalPushState;
          const tempOriginalReplaceState = state.originalReplaceState;
          
          window.history.pushState = tempOriginalPushState;
          window.history.replaceState = tempOriginalReplaceState;
          
          // 清空引用
          state.originalPushState = null;
          state.originalReplaceState = null;
          
        } catch (err) {
          console.error('[面包屑] 恢复History方法失败:', err);
        }
      } else {
        console.warn('[面包屑] 找不到原始History方法引用');
      }
      
      // 2. 最后移除清理事件监听器自身
      cleanupListeners.forEach(({ element, eventType, handler, options }) => {
        try {
          element.removeEventListener(eventType, handler, options);
        } catch (err) {
          console.error(`[面包屑] 移除清理监听器出错:`, err);
        }
      });
      
      // 清空清理监听器数组
      cleanupListeners.length = 0;
    }
    
    // 注册清理事件，并保存引用
    function registerCleanupEvents() {
      // 创建事件处理函数
      const pageTransitionHandler = () => {
        selfDestruct();
      };
      
      // Astro视图转换事件 - 保留这个作为后备
      const beforeSwapHandler = () => {
        selfDestruct();
      };
      
      // 页面卸载事件 - 保留这个作为后备
      const beforeUnloadHandler = () => {
        selfDestruct();
      };
      
      // 只监听统一的页面转换事件
      document.addEventListener("page-transition", pageTransitionHandler);
      
      // 保留Astro和页面卸载事件作为后备
      document.addEventListener("astro:before-swap", beforeSwapHandler, { once: true });
      window.addEventListener("beforeunload", beforeUnloadHandler, { once: true });
      
      // 保存清理事件引用，用于完全销毁
      cleanupListeners.push(
        { element: document, eventType: "page-transition", handler: pageTransitionHandler, options: null },
        { element: document, eventType: "astro:before-swap", handler: beforeSwapHandler, options: { once: true } },
        { element: window, eventType: "beforeunload", handler: beforeUnloadHandler, options: { once: true } }
      );
    }
    
    // 设置返回按钮功能
    function setupBackButton() {
      const backButton = document.querySelector('.breadcrumb-back-btn');
      
      if (!backButton) {
        return;
      }
      
      // 获取当前URL信息
      const url = new URL(window.location.href);
      const searchParams = url.search;
      
      // 根据是否有查询参数确定返回目标
      let targetHref;
      if (searchParams) {
        // 有查询参数，返回筛选页面
        targetHref = `/filtered${searchParams}`;
      } else {
        // 没有查询参数，返回默认路径
        targetHref = backButton.getAttribute('data-path') || '';
      }
      
      // 修改返回按钮属性，使其成为swup可识别的链接
      backButton.setAttribute('href', targetHref);
      
      // 如果支持swup，确保swup能处理此链接
      if (typeof window.swup !== 'undefined') {
        // 移除可能阻止swup处理的属性
        backButton.removeAttribute('data-no-swup');
        
        // 确保链接有正确的prefetch属性
        if (!backButton.hasAttribute('data-astro-prefetch')) {
          backButton.setAttribute('data-astro-prefetch', 'hover');
        }
      }
    }
    
    // 主初始化函数
    function init() {
      // 注册清理事件
      registerCleanupEvents();
      
      // 设置路径变化检测
      setupPathChangeDetection();
      
      // 执行初始更新
      updateBreadcrumbs();
      
      // 设置返回按钮
      setupBackButton();
      
      // 注册页面加载后的处理函数 - 仅当使用View Transitions或Swup时
      if (typeof document.startViewTransition !== 'undefined' || typeof window.swup !== 'undefined') {
        // 监听页面加载事件
        const pageLoadHandler = () => {
          // 重新执行一次更新
          updateBreadcrumbs();
          setupBackButton();
        };
        
        if (typeof document.startViewTransition !== 'undefined') {
          addListener(document, 'astro:page-load', pageLoadHandler);
        }
        
        if (typeof window.swup !== 'undefined') {
          addListener(document, 'swup:contentReplaced', pageLoadHandler);
        }
      }
    }
    
    // 判断DOM是否已加载
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", init, { once: true });
    } else {
      init();
    }
  })();
</script> 